package cn.bugstack.middleware.dynamic.thread.pool.sdk.trigger.job;

import cn.bugstack.middleware.dynamic.thread.pool.sdk.alarm.ThreadPoolAlarmService;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolAlarmEntity;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @author XiRui
 * @description 线程池数据上报任务
 * @create 2024-11-12 16:29
 */
public class ThreadPoolDataReportJob {

    private final Logger logger = LoggerFactory.getLogger(ThreadPoolDataReportJob.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;
    
    private final ThreadPoolAlarmService alarmService;

    public ThreadPoolDataReportJob(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry, ThreadPoolAlarmService alarmService) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
        this.alarmService = alarmService;
    }

    @Scheduled(cron = "0/20 * * * * ?")
    public void execReportThreadPoolList() {
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolList();
        registry.reportThreadPool(threadPoolConfigEntities);
        logger.info("动态线程池，上报线程池信息：{}", JSON.toJSONString(threadPoolConfigEntities));

        for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigEntities) {
            registry.reportThreadPoolConfigParameter(threadPoolConfigEntity);
            logger.info("动态线程池，上报线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));
            
            // 获取告警配置并检查告警
            ThreadPoolAlarmEntity alarmConfig = registry.getAlarmConfig(
                    threadPoolConfigEntity.getAppName(), 
                    threadPoolConfigEntity.getThreadPoolName());
            
            // 如果没有配置告警，则创建默认配置
            if (alarmConfig == null) {
                alarmConfig = new ThreadPoolAlarmEntity(
                        threadPoolConfigEntity.getAppName(), 
                        threadPoolConfigEntity.getThreadPoolName());
                alarmConfig.setAlarmEnabled(false);
            }
            
            // 检查告警
            alarmService.checkAndAlarm(threadPoolConfigEntity, alarmConfig);
        }
    }
}
